<?php
namespace Admin\Controller;
use Think\Controller;
class IndexController extends BaseController {
    public function index(){
		// 入口，已登录调到首页，未登录跳转到登陆
		if(session('?admin'))
			redirect(U('Base/welcome'));
		else
			redirect(U('Index/login'));
    }
	
	// 登录
	public function login(){
		$login['username'] = I('username');
		$login['password'] = I('password');
		$url = U('Base/welcome');
		if ($_SESSION['admin']){
			redirect($url);
		}
		if(IS_POST && !empty($login)){
			$adminObj = M('Admin');
			$login['password'] = xmd5($login['password']);
			$result = $adminObj->where("username='{$login['username']}' and password='{$login['password']}'")->find();
			if(empty($login['username']) || empty($login['password'])){
				$this -> assign('errmsg', '账号密码不能为空');
			}else{
				if($result){
					if($result['is_disable']!=0){
						$this -> assign('errmsg', '账号异常，请联系系统管理员');
					}else{
						if ($result['id'] == 1){
							$result['role_name'] = "超级管理员";
						}else{
							$roleObj = M("Role");
							$role = $roleObj->find($result['role_id']);
							$result['role_area'] = $role_area = explode(',', $role['role_area']);
							$result['role_name'] = $role['name'];
						}
						session('admin',$result);
						
						if(!empty(I('remember'))){
							cookie('admin_user', $login['username']);
						}else{
							cookie('admin_user', null);
						}
						
						$data['date'] = time();
						$result = $adminObj->where("id={$result['id']}")->save($data);
						
						redirect($url);
						exit;
					}
				}else{
					$this -> assign('errmsg', '账号或密码不对');
				}
			}
		}
		
		$this -> display();
	}
	
	//  退出
	public function logout(){
		session('admin',null);
		redirect(U('login'));		
	}
	
}